﻿using Alipay.AopSdk.Core.Domain;
using Alipay.AopSdk.Core.Request;
using Alipay.AopSdk.Core.Response;
using Alipay.AopSdk.Core;
using Alipay.AopSdk.F2FPay.Business;
using Alipay.AopSdk.F2FPay.Model;
using ThirdParty.Application.ThirdParty.Interfaces;
using ThirdParty.Application.Model.ViewModel.Request;
using ThirdParty.Application.Model.ViewModel.Response;
using Microsoft.Extensions.DependencyInjection;
using LDM.Business.Repository.Repository.Interfaces;
using ThirdParty.Application.Model;

namespace ThirdParty.Application.Alibaba
{
    /// <summary>
    /// 支付宝服务
    /// </summary>
    public class AliPayService : IAliPayService, IScoped
    {
        /// <summary>
        /// 系统配置参数
        /// </summary>
        public ISystemConfigRepository systemConfigRepository { protected get; set; }
        /// <summary>
        /// 支付宝面对面服务
        /// </summary>
        public IAlipayTradeService serviceClient = null;
        /// <summary>
        /// 支付宝默认支付服务
        /// </summary>
        public DefaultAopClient defaultAopClient = null;


        private static object DefaultAop_Lock = new object();

        public AliPayService()
        {

        }

        /// <summary>
        /// 获取面对面接口服务
        /// </summary>
        /// <returns></returns>
        public IAlipayTradeService CreateAlipayTradeInstance()
        {
            var systemConfig = systemConfigRepository.GetSystemConfig();
            serviceClient = F2FBiz.CreateClientInstance(systemConfig.ServerUrl, systemConfig.AlipayAppId, systemConfig.MerchantPrivateKey, AliPayHelp.version, AliPayHelp.sign_type, systemConfig.AlipayPublicKey, AliPayHelp.charset);
            return serviceClient;
        }       

        /// <summary>
        /// 创建支付宝默认支付服务
        /// </summary>
        /// <returns></returns>
        public DefaultAopClient CreateDefaultAopInstance()
        {
            if (defaultAopClient == null)
            {
                lock (DefaultAop_Lock)
                {
                    if (defaultAopClient == null)
                    {
                        var systemConfig = systemConfigRepository.GetSystemConfig();
                        defaultAopClient = new DefaultAopClient(systemConfig.ServerUrl, systemConfig.AlipayAppId, systemConfig.MerchantPrivateKey, "json", AliPayHelp.version, AliPayHelp.sign_type, systemConfig.AlipayPublicKey, AliPayHelp.charset, false);
                    }
                }
            }
            return defaultAopClient;
        }


        /// <summary>
        /// 创建二维码订单
        /// </summary>
        /// <param name="reqDto"></param>
        /// <returns></returns>
        public CreateQRCodeOrderRespDto AlipayCreateQRCodeOrder(AlipayCreateQRCodeOrderReqDto reqDto)
        {
            serviceClient = CreateAlipayTradeInstance();
            var systemConfig = systemConfigRepository.GetSystemConfig();
            reqDto.NotifyUrl = systemConfig.AliNotifyUrl;
            reqDto.AliPayPid = systemConfig.AlipayPid;
            var builderTradePrecreate = AlipayCreateQRCodeOrderReqDto.GetAlipayTradePrecreateContentBuilder(reqDto);
            AlipayF2FPrecreateResult precreateResult = serviceClient.TradePrecreate(builderTradePrecreate, systemConfig.AliNotifyUrl);
            string result = "";
            switch (precreateResult.Status)
            {
                case ResultEnum.SUCCESS:
                    result = precreateResult.response.QrCode;
                    break;
                case ResultEnum.FAILED:
                    result = precreateResult.response.Body;
                    break;
                case ResultEnum.UNKNOWN:
                    if (precreateResult.response == null)
                    {
                        result = "配置或网络异常，请检查后重试";
                    }
                    else
                    {
                        result = "系统异常，请更新外部订单后重新发起请求";
                    }
                    break;
            }
            return new CreateQRCodeOrderRespDto { Code = (int)precreateResult.Status, OrderNum = precreateResult.response.OutTradeNo, ResultMsg = result };
        }


        /// <summary>
        ///  获取手机网站调用支付宝支付
        /// </summary>
        /// <param name="trade_no">外部订单号，商户网站订单系统中唯一的订单号</param>
        /// <param name="orderName">订单名称</param>
        /// <param name="amout">付款金额</param>
        /// <param name="desc">商品描述</param>
        /// <param name="quitUrl">支付中途退出返回商户网站地址</param>
        /// <param name="returnUrl">设置支付完成同步回调地址</param>
        /// <param name="setNotifyUrl">设置支付完成异步通知接收地址</param>
        /// <returns></returns>
        public string AlipayCreateWapOrder(string trade_no, string orderName, string amout, string desc, string quitUrl, string returnUrl, string setNotifyUrl)
        {
            string reulst = string.Empty;
            // 组装业务参数model
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.Body = desc.Trim();
            model.Subject = orderName.Trim();
            model.TotalAmount = amout.Trim();
            model.OutTradeNo = trade_no.Trim();
            model.ProductCode = "QUICK_WAP_WAY";
            model.QuitUrl = string.IsNullOrWhiteSpace(quitUrl) ? "" : quitUrl.Trim();
            model.TimeExpire = DateTime.Now.AddMinutes(10).ToString("yyyy-MM-dd HH:mm");
            model.TimeoutExpress = "10m";
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            request.SetReturnUrl(returnUrl);
            if (string.IsNullOrWhiteSpace(setNotifyUrl))
            {
                var systemConfig = systemConfigRepository.GetSystemConfig();
                request.SetNotifyUrl(systemConfig.AliNotifyUrl);
            }
            request.SetBizModel(model);
            try
            {
                defaultAopClient = CreateDefaultAopInstance();
                AlipayTradeWapPayResponse response = defaultAopClient.PageExecute(request, null, "post");
                reulst = response.Body;
            }
            catch (Exception exp)
            {
                throw exp;
                ///TODO :添加日志
            }
            return reulst;
        }

        /// <summary>
        /// 交易订单查询
        /// </summary>
        /// <param name="tradeNo">商户订单号，和交易号不能同时为空</param>
        /// <param name="zfbTradeNo">支付宝交易号，和商户订单号不能同时为空</param>
        /// <param name=""></param>
        public string AlipayWapQuery(string tradeNo, string zfbTradeNo)
        {
            var result = string.Empty;
            string out_trade_no = tradeNo.Trim();
            string trade_no = zfbTradeNo.Trim();
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            model.OutTradeNo = out_trade_no;
            model.TradeNo = trade_no;
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.SetBizModel(model);
            try
            {
                defaultAopClient = CreateDefaultAopInstance();
                AlipayTradeQueryResponse response = defaultAopClient.Execute(request);
                result = response.Body;
            }
            catch (Exception exp)
            {
                throw exp;
            }
            return result;
        }
    }

}
